angular.module('winedetailcontrollers',[])
  .controller('WineDetailCtrl',function($scope,$rootScope,$cordovaStatusbar,$stateParams,$cordovaFileTransfer,$ionicActionSheet,$state,$timeout,$cordovaMedia,Video,Magazine,Loading,Wine,WineComment,Storage,History,ENV,Toast){

    var memberId = Storage.get("member").member_id;
    var wineId =$stateParams['wineId'];
    $scope.picPath = ENV.picPath;
    var recommendInfo = [{member_id:memberId,wine_id:wineId}];

    /***************查看酒款大图，并保存************/
    $scope.showBigWineImg = function(index){
      var items = [];
      var lookImageList = $scope.wine.wineImgsWithWh;
      var pswpElement = document.querySelectorAll('.pswp')[0];
      for(i=0;i<lookImageList.length;i++){
        var temp = {
          src:$scope.picPath+"big_"+lookImageList[i].src,
          w:lookImageList[i].w,
          h:lookImageList[i].h
        };
        items.push(temp);
      }
      var options = {
        index: index,
        history: false,
        focus: false,
        loop: false,
       /* pinchToClose:false,
        closeOnVerticalDrag:false,*/
        showAnimationDuration: 100,
        hideAnimationDuration: 100,
        backButtonHideEnabled:true,
        captionAndToolbarFlipPosition:true,
        loadingIndicatorDelay:100
      };
      $rootScope.gallery  = new PhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options);
      $rootScope.gallery.init();
      //$cordovaStatusbar.hide();
    }
    $rootScope.downloadHomeImg = function(){
      var url = $rootScope.gallery.currItem.src;
      var timestamp=new Date().getTime();
      var targetPath = cordova.file.externalRootDirectory+"winelife/winelife_product_"+timestamp+".jpg";
      var trustHosts = true;
      var options = {};
      $ionicActionSheet.show({
        buttons: [
          {text: '保存到手机相册'}
        ],
        cancelText: '取消',
        buttonClicked: function (index) {
          if(index==0){
            $cordovaFileTransfer.download(url, targetPath, options, trustHosts)
              .then(function(result) {
                Toast.showMessage("保存成功");
              }, function(err) {
                Toast.showMessage("保存成功");
              }, function (progress) {
              });
          }
          return true;
        }
      });
    }
    //单击缩小图片
    $rootScope.smallPicture = function(){
      $rootScope.gallery.close();
     // $cordovaStatusbar.show();
    }
    /*******播放音频开始****************/

    var media = '';
    var playAudioing = false;
    $scope.playAudio = function(){
      if(!playAudioing){
        playAudioing = true;
        var audioPath = ENV.audioPath+$scope.wine.wine_audio;
        media = $cordovaMedia.newMedia(audioPath);
        media.play();
        $timeout(function () {
          playAudioing = false;
        }, 3000);
      }
    };
    $scope.$on('$ionicView.beforeLeave',function(){
      playAudioing = false;
      media.stop();
      media.release();
    });
    $scope.$on('$ionicView.leave',function(){
      playAudioing = false;
      media.stop();
      media.release();
    });
    /*******播放音频结束****************/
   //进入页面时获取到酒款的数量
    $scope.$on('$ionicView.beforeEnter',function(){
      memberId = Storage.get("member").member_id;
      if($scope.wine!=undefined){
        WineComment.getCommentCount(wineId,memberId);
      }
    })
    $scope.$on('Wine.commentCountUpdated',function(){
      var result = WineComment.getCommentCountJson();
      $scope.wine.wine_comment_num = result.wine_comment_num;
      $scope.wine.mcStatus = result.mcStatus;
    })
  //加入推荐酒单
  $scope.add2WineRecommend = function(){
    Wine.add2WineRecommend(recommendInfo);
  };
  $scope.$on('Wine.add2WineRecommendUpdated',function(){
    var result = Wine.getAddWineRecommendJson();
    Toast.showMessage(result.insertWineMsg);
  });
    //跳转到酒庄故事
    $scope.readChateauStory = function(){
      Magazine.getBookDetail($scope.wine.wine_chateau_story);
      //wine.wine_chateau_story
    };
    $scope.$on('Book.hasBookDetailUpdated',function(){
      var flag = Magazine.hasBookDetail();
      if(flag){
        $state.transitionTo('book-details',{'bdId':$scope.wine.wine_chateau_story});
      }else{
        Toast.showMessage("酒庄故事不存在");
      }
    });
    //跳转到酒庄视频
    $scope.seeWineVideo = function(){
      Video.getVideoById($scope.wine.wine_video_url);
      //wine.wine_video_url
    };
    $scope.$on('Video.hasVideoUpdated',function(){
      var flag = Video.hasVideoOrNot();
      if(flag){
        $state.transitionTo('video-details',{'videoId':$scope.wine.wine_video_url});
      }else{
        Toast.showMessage("酒庄视频不存在");
      }
    });
  //获取酒款详情---------->
    $scope.$on('$ionicView.loaded', function () {
      Loading.showLoading();
      Wine.getWineDetailById(memberId,wineId);
    });
    $scope.$on('Wine.WineDetailUpdated',function(){
      Loading.hideLoading();
      $scope.wine  = Wine.getWineDetailJson();
      console.log($scope.wine);
    });
  //收藏
    var collectWineing = false;
  $scope.collectWine = function(){
    if(!collectWineing){
      Wine.collectWine(wineId,memberId);
      collectWineing = true;
    }
  };
  //收藏成功后的回调方法
  $scope.$on('Wine.collectBWineUpdated',function(){
    collectWineing = false;
    var result  = Wine.getCollectWineJson();
    $scope.wine.mcStatus  = result.awcStatus;
    Toast.showMessage(result.awcMsg);
  });
    //返回
    $scope.goback = function(){
      History.goback();
    };

    //改变数字的显示，添加逗号分割
    $scope.getFormatNum = function (num) {
      return formatNum(num);
    };
})









  //酒款评论Controller
  .controller('WineCommentCtrl',function($scope,$stateParams,$ionicPopup,$state,Storage,WineComment,History,ENV,Toast,Loading){

        var wineId = $stateParams['wineId'];
        var memberId = '';
        $scope.picPath = ENV.picPath;

        var isFirstIn = true;
        $scope.$on('$ionicView.beforeEnter',function(){
          memberId = Storage.get('member').member_id;
          if(isFirstIn){
            Loading.showLoading();
            isFirstIn = false;
          }
        //获取评论列表
        WineComment.getCommentList(wineId,memberId);
    });
    //删除评论
    var deleteIndex = '';
    $scope.deleteComment = function(commentId,index){
      $ionicPopup.confirm({
        template: '<p style="text-align: center;font-size:16px;">确定要删除该评论吗？</p>',
        cancelText: '取消',
        okText: '确定',
        okType: 'hd-red-btn',
        cancelType: 'cancel-esc-btn'
      }).then(function (res) {
        if (res) {
          Loading.showLoading();
          WineComment.deleteComment(commentId,memberId,wineId);
          deleteIndex = index;
        }
      });

    }
    $scope.$on('WineComment.deleteCommentUpdated',function(){
      Loading.hideLoading();
      var result = WineComment.getDelCommentJson();
      if(result.dwmCommentStatus){
        $scope.commentList.splice(deleteIndex,1);
      }
      Toast.showMessage(result.dwmCommentMsg);
    });
        //新增评论
        $scope.comment={
          newComment:''
        };
      $scope.$on('Wine.CommentListUpdated',function() {
        Loading.hideLoading();
        $scope.$broadcast('scroll.refreshComplete');
        $scope.commentList = WineComment.getCommentListJson();
        $scope.memberInfo =WineComment.getMemberInfo();
      });
    //发表评论
    $scope.publishComment = function(){
      if($scope.comment.newComment == ''){
        Toast.showMessage("请输入评论内容");
      }else{
        WineComment.publishComment(wineId,memberId,$scope.comment.newComment);
        $scope.comment.newComment = '';//使得输入框中的值为空
      }
    };
    //下拉刷新
    $scope.doRefresh= function(){
      WineComment.getCommentList(wineId,memberId);
    }
    //加载更多
    $scope.loadMore = function(){
      WineComment.getMoreCommentList(wineId,memberId);
    }
    $scope.hasNextPage = function(){
      return WineComment.hasNextPage();
    }
    $scope.$on('Wine.MoreCommentListUpdated',function() {
      $scope.$broadcast('scroll.infiniteScrollComplete');
      $scope.commentList = WineComment.getCommentListJson();
      console.log($scope.commentList.length);
    });
    //请求网络数据完成之后
    $scope.$on('Wine.publishCommentUpdated', function() {
      var newComment = WineComment.getNewComment();

      if(newComment.awCommentStatus){
        $scope.commentList.unshift(newComment);
      }else{
      }
      Toast.showMessage(newComment.awCommentMsg);
    });
    //返回
    $scope.goback = function(){
      History.goback();
    }
  })
;
